import os
import shutil
import subprocess

from git import Repo, GitCommandError, InvalidGitRepositoryError
from platformdirs import user_documents_dir



# 获取存档
repo_path = os.getcwd()

try:
    repo = Repo(repo_path)

except InvalidGitRepositoryError:
    print("当前目录不是 Git 仓库，正在初始化 git...")
    repo = Repo.init(repo_path)

    remote_url = "https://gitee.com/FBIHoldYouFire/terraria_server.git"
    repo.create_remote('origin', url=remote_url)
    print("已添加远程仓库 origin")


try:
    origin = repo.remote(name='origin')
    origin.pull("savings")
    print("获取成功")
except GitCommandError as e:
    print("❌ Git pull 失败")
    print(f"命令: {e.command}")
    print(f"状态码: {e.status}")
    print(f"错误输出:\n{e.stderr}")

# 复制存档到目标
files = os.listdir('./')
source_file = [file for file in files if file.endswith('.wld')]

if not source_file:
    print("未找到存档文件")
    exit(0)

print(f"找到存档：{source_file[0]}")

# 获取文档目录
try:
    document_path = user_documents_dir()
except Exception as e:
    print(f"获取存档目录失败: {e}")
    exit(1)

target_folder = os.path.join(document_path, "My Games", "Terraria", "Worlds")
print(f"目标存档位置：{target_folder}")

target_file = os.path.join(target_folder, source_file[0])

# 正在备份存档
filename = source_file[0]
name, ext = os.path.splitext(filename)
dst_path = os.path.join("./backups", filename)

counter = 1

while os.path.exists(dst_path):
    new_filename = f"{name}_{counter}{ext}"
    dst_path = os.path.join("./backups", new_filename)
    counter += 1

shutil.copy2(target_file, dst_path)
print(f"备份存档到：./backups/{dst_path}")


if os.path.exists(target_file):
    os.remove(target_file)
# 执行文件移动
try:
    shutil.move(source_file[0], target_folder)
    print(f"存档已成功移动到：{target_file}")
except Exception as e:
    print(f"移动存档时出错: {e}")

# 打开服务端
print("正在启动服务端")
exe_path = os.path.join(os.getcwd(), "server", "TerrariaServer.exe")  # 获取绝对路径

if not os.path.exists(exe_path):
    print(f"找不到服务器: {exe_path}")
else:
    try:
        # 直接传递路径，不使用 shell=True
        result = subprocess.run([exe_path], check=True, capture_output=True, text=True)
    except subprocess.CalledProcessError as e:
        print(f"启动失败，返回码: {e.returncode}")
        print(f"错误输出: {e.stderr}")
    except Exception as e:
        print(f"发生异常: {e}")

# 保存存档

